package designpatterns.structure;

import java.util.ArrayList;
import java.util.List;

/**
 * 组合模式
 * 有时又叫作部分-整体模式，它是一种将对象组合成树状的层次结构的模式，
 * 用来表示“部分-整体”的关系，使用户对单个对象和组合对象具有一致的访问性。
 * 使用场景：部分、整体场景，如树形菜单，文件、文件夹的管理
 * 优点：1、高层模块调用简单。2、节点自由增加。
 * 缺点：在使用组合模式时，其叶子和树枝的声明都是实现类，而不是接口，违反了依赖倒置原则。
 *
 * @author jack.wu
 * @since 2019/9/23
 */
public class CompositeTest {
    public static void main(String[] args) {
        // ceo
        Employee ceo = new Employee("John", "CEO", 30000);
        // 首席销售
        Employee headSales = new Employee("Robert", "Head Sales", 20000);
        // 营销主管
        Employee headMarketing = new Employee("Michel", "Head Marketing", 20000);
        // 店员
        Employee clerk1 = new Employee("Laura", "Marketing", 10000);
        Employee clerk2 = new Employee("Bob", "Marketing", 10000);
        // 销售主管
        Employee salesExecutive1 = new Employee("Richard", "Sales", 10000);
        Employee salesExecutive2 = new Employee("Rob", "Sales", 10000);
        // ceo 直接下属
        ceo.add(headSales);
        ceo.add(headMarketing);
        // 首席销售直接下属
        headSales.add(salesExecutive1);
        headSales.add(salesExecutive2);
        // 营销主管直接下属
        headMarketing.add(clerk1);
        headMarketing.add(clerk2);

        //打印该组织的所有员工
        System.out.println(ceo);
        for (Employee headEmployee : ceo.getSubordinates()) {
            System.out.println(headEmployee);
            for (Employee employee : headEmployee.getSubordinates()) {
                System.out.println(employee);
            }
        }
    }


}

class Employee {
    private String name;
    private String dept;
    private int salary;
    /**
     * 下属
     */
    private List<Employee> subordinates;

    public Employee(String name, String dept, int salary) {
        this.name = name;
        this.dept = dept;
        this.salary = salary;
        subordinates = new ArrayList<Employee>();
    }

    public void add(Employee e) {
        subordinates.add(e);
    }

    public void remove(Employee e) {
        subordinates.remove(e);
    }

    public List<Employee> getSubordinates() {
        return subordinates;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "Name='" + name + '\'' +
                ", Dept='" + dept + '\'' +
                ", Salary=" + salary +
                ", Subordinates=" + subordinates +
                '}';
    }
}
